<template>
  <div class="pop-dialog-container">
    <div class="pop-dialog-main">
      <el-form label-position="right" :model="facilityForm" :label-width="formLabelWidth" ref="facilityFormRef" :rules="rules">
        <el-row>
          <el-col :span="11">
            <el-form-item label="公共设施名称" prop="name">
              <el-input v-model="facilityForm.name" placeholder="请输入公共设施名称" maxlength="255"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="楼栋名称" prop="buildingName">
              <el-input v-model="facilityForm.buildingName" placeholder="请选择楼栋名称" readonly="readonly">
                <template #suffix>
                  <el-icon @click="findBuilding"><Search/></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="位置" prop="location">
              <el-input v-model="facilityForm.location" placeholder="请输入位置" maxlength="255"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="最后保养日期" prop="lastMaintenanceDate">
              <el-date-picker
                  v-model="facilityForm.lastMaintenanceDate" type="date" placeholder="最后保养日期" value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="状态" prop="status">
              <el-select v-model="facilityForm.status" placeholder="请选择状态">
                <el-option label="正常" :value="10"></el-option>
                <el-option label="异常" :value="20"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="pop-dialog-footer">
      <el-row>
        <el-col :span="11" :offset="6">
          <div class="form-button-container">
            <el-button type="primary" @click="onSave">保存</el-button>
            <el-button @click="onReset">重置</el-button>
            <el-button type="primary" @click="onBack">关闭</el-button>
          </div>
        </el-col>
      </el-row>
    </div>
    <el-dialog v-model="buildingSelectorVisible" v-if="buildingSelectorVisible" title="楼栋信息选择器(双击行选中)" :top="dialogTop" :width="dialogWidth">
      <building-selector @building-selected-event="handleBuildingSelectedEvent">
      </building-selector>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {defineEmits, defineProps, inject, onMounted, reactive, ref, toRefs} from 'vue';
import facilityApi from '@/api/facilityApi'
import type {FormInstance} from 'element-plus';
import {ElMessage} from 'element-plus'
import type {FacilityForm} from "@/types/req/facilityForm";
import type {Result} from '@/types/result'
import type {Facility} from "@/types/resp/facility";
import type {Id} from "@/types/id";
import { Search } from '@element-plus/icons-vue';
import BuildingSelector from "@/views/building/BuildingSelector.vue";

const props = defineProps<Id>()
const facilityFormRef = ref<FormInstance | null>(null);
const facilityForm = reactive<FacilityForm>({
  name: '',
  buildingId: 0,
  buildingName: '',
  location: '',
  lastMaintenanceDate: '',
  status: undefined,
})
const buildingSelectorVisible = ref<boolean>(false)
const emit = defineEmits<{
  (e: 'resetFacilityAddEvent'): void;
  (e: 'closeFacilityAddEvent', data?: { search: boolean }): void;
}>()

const rules = reactive({
});
const dialogTop = ref<string>('')
const dialogWidth = ref<string>('')
const formLabelWidth = ref<string>('')

onMounted(() => {
  if (props.id) {
    initFacilityFormById(props.id)
  }
  const globalState = inject('globalState', {} as { dialogWidth?: string, dialogTop?: string, formLabelWidth?: string })
  if (!globalState) {
    throw new Error('globalState is not provided');
  }
  const globalStateRefs = toRefs(globalState)
  if (globalStateRefs.formLabelWidth) {
    formLabelWidth.value = globalStateRefs.formLabelWidth.value || ''
  }
  if (globalStateRefs.dialogWidth) {
    dialogWidth.value = globalStateRefs.dialogWidth.value || ''
  }
  if (globalStateRefs.dialogTop) {
    dialogTop.value = globalStateRefs.dialogTop.value || ''
  }
});

const initFacilityFormById = async (id: number) => {
  const resp: Result<Facility> = await facilityApi.findById(id)
  if (resp && resp.code === 1 && resp.data) {
    Object.assign(facilityForm, resp.data)
  }
}

const onReset = () => {
  if (facilityFormRef.value) {
    facilityFormRef.value.resetFields()
  }
  emit('resetFacilityAddEvent')
}

const onSave = () => {
  if (!facilityFormRef.value) {
    return
  }
  facilityFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      const resp: Result<void> = await facilityApi.save(facilityForm)
      if (resp && resp.code === 1) {
        ElMessage.success('保存成功')
        emit('closeFacilityAddEvent', {search: true})
      } else {
        ElMessage.error('保存失败:' + (resp.msg ? resp.msg : ''))
      }
    }
  })
}

const findBuilding = () => {
  buildingSelectorVisible.value = true
}

const handleBuildingSelectedEvent = (selectedBuilding: any) => {
  buildingSelectorVisible.value = false
  if (selectedBuilding && 'buildingId' in selectedBuilding && facilityForm.buildingId !== selectedBuilding['buildingId']) {
    facilityForm.buildingId = selectedBuilding['buildingId']
    facilityForm.buildingName = selectedBuilding['buildingName']
  }
}

const onBack = () => {
  emit('closeFacilityAddEvent')
}
</script>

<style lang="scss">
</style>
